import { ref, computed, onMounted } from 'vue'
import { defineStore } from 'pinia'
import { localStore } from '@/utils/storage'

type User = {
  userId?: string
  name?: string
  role?: string
}

export const useUserStore = defineStore('user', () => {
  const user = ref<User>()
  const role = computed(() => user.value?.role)
  function login(data: User) {
    user.value = data
    localStore.set('user', data)
  }
  function logout() {
    user.value = undefined
    localStore.remove('user')
  }

  onMounted(() => {
    user.value = localStore.get('user')
  })

  return { user, role, login, logout }
})
